package com.example.shardingsphere.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shardingsphere.entity.Order;
import com.example.shardingsphere.mapper.OrderMapper;
import com.example.shardingsphere.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用于测试 水平分库，水平分表
 */
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @PostMapping("/test")
    public Object test(@RequestBody Order order) {
        List<Order> orderList = orderMapper.test(order.getUserId());
//        Long count = orderService.count();
        return JSONUtil.toJsonStr(orderList);
    }


    @PostMapping("/add")
    public Object createOrder(@RequestBody Order order) {
        return orderService.save(order);
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orderService.getById(id);
    }

    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.list();
    }

    @PutMapping("/{id}")
    public boolean updateOrder(@PathVariable Long id, @RequestBody Order order) {
        order.setOrderId(id);
        return orderService.updateById(order);
    }

    @DeleteMapping("/{id}")
    public boolean deleteOrder(@PathVariable Long id) {
        return orderService.removeById(id);
    }

    @GetMapping("/page")
    public Page<Order> getOrdersByPage(@RequestParam int current, @RequestParam int size) {
        Page<Order> page = new Page<>(current, size);
        return orderService.page(page, new QueryWrapper<>());
    }
}